package com.it.fastpay.interceptor;

import com.it.fastpay.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

import java.io.PrintWriter;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static final String SESSION_LOGIN_KEY="loginUser";

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/fastpaygoodsIlike", uri);
         //如果是秒杀的请求，才必须需要登录
        if (match) {
            HttpSession session = request.getSession();
            //获取登录的用户信息
            MemberRespVo attribute = (MemberRespVo) session.getAttribute(SESSION_LOGIN_KEY);
            if (attribute != null) {
                //把登录后用户的信息放在ThreadLocal里面进行保存
                loginUser.set(attribute);
                return true;
            } else {
                //未登录，返回登录页面
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                //TODO 请填写自己的跳转登录页面
                out.println("<script>alert('请先进行登录，再进行后续操作！');location.href='你的登录页面'</script>");
                // session.setAttribute("msg", "请先进行登录");
                // response.sendRedirect("html");
                return false;
            }
        }
        //不是秒杀，直接放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
